<!-- eslint-disable vue/require-valid-default-prop -->
<template>
  <a-drawer
    :title="title"
    width="850px"
    placement="right"
    :closable="false"
    :visible="visible"
    @close="
      () => {
        this.visible = false
      }
    "
  >
    <!-- <div style="margin-top: 10px;">
      <a-radio-group v-model="isvalue" button-style="solid">
        <a-radio-button value="1">
          高开
        </a-radio-button>
        <a-radio-button value="0">
          低开
        </a-radio-button>

      </a-radio-group>
    </div> -->
    <div style="position: relative" v-loading="loading">
      <div id="print-b" ref="pdfContent">
        <div v-for="(elment, dex) in list" :key="dex" style="padding: 20px">
          <a-row
            style="margin-left: 40px; font-size: 26px; margin-top: 90px; font-weight: 550; color: #000 !important;margin-bottom: 5px;"
            v-if="isvalue=='1'"
          >{{ '安徽省万生中药饮片有限公司销售清单(随货同行)' || '' }}</a-row
          >
          <a-row class="row" :style="isvalue=='1'?'':'margin-top:134px;'">
            <a-col :span="7">
              <span>发货日期：</span>{{ data.DTime ? moment(data.DTime).format('YYYY年MM月DD日') : '' }}
            </a-col>
            <a-col :span="7"> <span>订单号：</span>{{ data.SourceVoucherCode }} </a-col>
            <a-col :span="7"> <span>发货编号：</span>{{ data.ShipmentNumber }} </a-col>
            <div style="position: absolute;right: 0;top: -23px;display: flex;">
              <vue-qr
                :whiteMargin="false"
                :text="codeValue"
                :size="100"
                :margin="0"
                :correctLevel="1"
                :auto-color="true"
                colorDark="#000"
                :dot-scale="1"
              ></vue-qr>
              <div style="text-align: center;width: 18px;">请扫码签收</div>
            </div>
          </a-row>
          <a-row class="row">
            <a-col :span="14"> <span> 购货单位：</span>{{ data.CusName }} </a-col>
            <a-col :span="7"> <span>销售部门：</span>{{ data.DeptName }} </a-col>
          </a-row>
          <a-row class="row">
            <a-col :span="24"> <span>地&emsp;&emsp;址：</span>{{ data.CusAddress }} </a-col>
          </a-row>
          <a-row class="row">
            <a-col :span="24"> <span>备&emsp;&emsp;注：</span>{{ strCat(data.Remark,Info.Memo) }} </a-col>
          </a-row>
          <table border="1" style="width: 100%; color: #000;border: 1px solid #000;font-size: 12px;">
            <thead :class="elment.length>8?'thead':['thead','lhthead']">
              <tr>
                <td>序号</td>
                <td v-for="item in data.columns" :key="item.dataIndex">
                  {{ item.title }}
                </td>
              </tr>
            </thead>
            <tbody :class="elment.length>8?'tbody':['tbody','lhtbody']">
              <tr v-for="(item, index) in elment" :key="index">
                <td>{{ dex*27+(index + 1) }}</td>
                <td v-for="val in data.columns" :key="val.dataIndex + index">

                  <div v-if="val.dataIndex == 'Quantity'" style="padding: 0px 5px; box-sizing: border-box">
                    {{ Number(item[val.dataIndex]) || '&nbsp;' }}
                  </div>
                  <div v-else-if="val.dataIndex == 'ManufactureDate'" style="padding: 0px 5px; box-sizing: border-box">
                      {{ toDate(item[val.dataIndex]) }}
                    </div>
                  <div
                    v-else-if="val.dataIndex == 'iInvRCost'"
                    style="text-align: right; padding: 0px 5px; box-sizing: border-box"
                  >
                    {{ Number(item[val.dataIndex]).toFixed(2) || '&nbsp;' }}
                  </div>
                  <div
                    v-else-if="val.dataIndex == 'SumiInvRCost'"
                    style="text-align: right; padding: 0px 5px; box-sizing: border-box"
                  >
                    <el-statistic
                      group-separator=","
                      :precision="2"
                      :value="Number(item[val.dataIndex]) || 0"
                    ></el-statistic>
                  </div>
                  <div v-else>{{ item[val.dataIndex] || '&nbsp;' }}</div>
                </td>

              </tr>
              <tr>
                <td>小计</td>
                <td :colspan="cspan">{{ numberParseChina(getAmount(totalAmount(elment))) }}</td>
                <td style="padding: 0px 5px">{{ totalQuantity(elment) || '&nbsp;' }}</td>
                <td style="text-align: right; padding: 0px 5px">{{ '&nbsp;' }}</td>
                <td style="text-align: right; padding: 0px 5px">
                  <el-statistic group-separator="," :precision="2" :value="getAmount(totalAmount(elment))"></el-statistic>
                </td>
                <td>&emsp;</td>
                <td>&emsp;</td>
                <td>&emsp;</td>
                <!-- //增加保质期至单元格 -->
                <td v-if="content.isExpiryDate">&emsp;</td>
                <!-- <td v-if="cspan>3">&emsp;</td> -->
                <td v-if="content.isRemark">&emsp;</td>
              </tr>
              <tr>
                <td>合计</td>
                <td :colspan="cspan">{{ numberParseChina(getAmount(totalAmount(list,true))) }}</td>
                <td style="padding: 0px 5px">{{ totalQuantity(list,true) || '&nbsp;' }}</td>
                <td style="text-align: right; padding: 0px 5px">{{ '&nbsp;' }}</td>
                <td style="text-align: right; padding: 0px 5px">
                  <el-statistic group-separator="," :precision="2" :value="getAmount(totalAmount(list,true))"></el-statistic>
                </td>
                <td>&emsp;</td>
                <td>&emsp;</td>
                <td>&emsp;</td>
                 <!-- //增加保质期至单元格 -->
                <td v-if="content.isExpiryDate">&emsp;</td>
                <!-- <td v-if="cspan>3">&emsp;</td> -->
                <td v-if="content.isRemark">&emsp;</td>
              </tr>
            </tbody>
          </table>
          <a-row v-if="type === 'downLoad'" class="row" style="display: flex;align-items: center;">
            <a-col :span="14"> &emsp;签收人签字：
              <img style="height: 71px;transform: rotate(-90deg);" v-if="Info.Sign" :src="Info.Sign" alt="">
            </a-col>
            <!-- <a-col :span="5"> 本页合计：{{ data.Auditor || '' }} </a-col>
            <a-col :span="5"> 价格合计：{{ data.Custodian || '' }} </a-col>             -->
          </a-row>
          <a-row class="row">
            <a-col :span="5"> &emsp;制单人：{{ data.Maker || '' }} </a-col>
            <a-col :span="5"> 复核人：{{ data.Auditor || '' }} </a-col>
            <a-col :span="5"> 保管员：{{ data.Custodian || '' }} </a-col>
            <a-col :span="5"> 收货人：{{ data.Geter || '' }} </a-col>
            <a-col :span="4"> 会计： {{ data.Treasurer || '' }}</a-col>
          </a-row>
          <a-row class="row" :gutter="20">
            <a-col :span="5">白联：存根联</a-col>
            <a-col :span="5">红联：随货同行</a-col>
            <a-col :span="5">蓝联：换票联</a-col>
            <a-col :span="5">绿联：记账联</a-col>
            <a-col :span="4">黄联：仓库联</a-col>
          </a-row>
          <a-row class="row">
            <a-col :span="18"> 药品上市许可持有人：安徽省万生中药饮片有限公司 </a-col>
            <a-col :span="6" style="text-align: right;">  第{{ dex+1 }}页共{{ list.length }}页</a-col>
          </a-row>
          <div style="page-break-after: always"></div>
        </div>

        <div v-if="type === 'downLoad'" style="padding: 20px">
          <a-row class="row" v-if="imgList.length">
            <a-col :span="4" v-for="(item, inx) in imgList" :key="inx">
              <img :src="item" style="padding:5px;width:100%;height:auto">
            </a-col>
          </a-row>
        </div>

      </div>
    </div>
    <div style="height: 50px"></div>
    <div
      style="
          position: fixed;
          bottom: 0;
          right: 0;
          bordertop: 1px solid #e9e9e9;
          padding: 10px 16px;
          background: #fff;
          width: 850px;
          text-align: right;
        "
    >
      <div v-if="type === 'view'" style="display: inline-block;"><span style="font-weight: bold;color: #000;">高开：</span><a-switch default-checked @change="switchonChange" /></div>
      <a-button v-if="type === 'view'" type="primary" @click="handleCommand('单据信息')" style="margin-left: 10px">微信分享</a-button>
      <a-button v-if="type === 'view'" type="primary" v-print="print" style="margin-left: 10px">打印</a-button>
      <a-button v-if="type === 'downLoad'" type="primary" @click="downloadPage" style="margin-left: 10px">下载</a-button>
      <!-- <a-button type="danger" style="margin-left: 10px" @click="isview = false" v-show="isview">编辑备注</a-button>
        <a-button type="primary" style="margin-left: 10px" @click="isview = true" v-show="!isview">保存备注</a-button> -->
    </div>
    <a-modal
      title="请使用微信扫一扫"
      :visible="dialogVisible"
      width="300px"
      :ok-button-props="{ style: { display: 'none' } }"
      @cancel="
        () => {
          this.dialogVisible = false
        }
      "
    >
      <div style="display: flex; justify-content: center">
        <!-- :logoSrc="require('@/assets/titlelogo.png')" -->
        <vue-qr :text="qrValue" :logoScale="0.2" :size="200"></vue-qr>
      </div>
    </a-modal>
    </div>
  </a-drawer>
</template>

<script>
import VueQr from 'vue-qr'
import moment from 'moment'
import { downloadPDF } from "@/utils/htmlToPdf.js";

export default {
  // props: {
  //   data: {
  //     type: Object,
  //     require: false,
  //     default: () => {},
  //   },
  // },
  components: {
    VueQr
  },
  data () {
    return {
      cspan:3,
      title:'查看',
      isvalue: '1',
      isview: true,
      visible: false,
      inputValue: '',
      loading: false,
      data: {},
      qrValue: '',
      valueId: '',
      codeValue: '',
      dialogVisible: false,
      content: {},
      print: {
        id: 'print-b',
        popTitle: ''
      },
      Info: {},
      imgList: [],
      tableInfo: {},
      list: [],
      type:'view'//view 查看    downLoad 下载
    }
  },
  computed: {},
  methods: {
    strCat(str0,str1){
      if(str0==str1){
        return str0
      }else{
        return str0+' '+str1
      }
    },
    toDate(val){
      let _tmp = val?val.split(' '):'';
      if(_tmp.length==2){
        let _sub = _tmp[0].split('/')
        return _sub[2]+'-'+_sub[0]+'-'+_sub[1]
      } else {
        return val
      }
    },
    switchonChange (a) {
      console.log(a)
      if (a) {
        this.isvalue = '1'
      } else {
        this.isvalue = '0'
      }
    },
    totalQuantity (list, isTrue = false) {
      if (isTrue) {
        let num = 0
        const arr = list || []
        arr.forEach((val) => {
          val.forEach(item => {
            num = Number(item.Quantity || 0) + num
          })
        })
        return num.toFixed(4)
      }
      let num = 0
      const arr = list || []
      arr.forEach((item) => {
        num = Number(item.Quantity || 0) + num
      })
      return num.toFixed(4)
    },
    totalPrice (list) {
      let num = 0
      const arr = list || []
      arr.forEach((item) => {
        num = Number(item.iInvRCost || 0) + num
      })
      return num.toFixed(2)
    },
    totalAmount (list, isTrue = false) {
      if (isTrue) {
        let num = 0
        const arr = list || []
        arr.forEach((val) => {
          val.forEach(item => {
            num = Number(item.SumiInvRCost || 0) + num
          })
        })
        return num
      }
      let num = 0
      const arr = list || []
      arr.forEach((item) => {
        num = Number(item.SumiInvRCost || 0) + num
      })
      return num
    },
    // 微信分享按钮
    handleCommand (command) {
      // let baseUrl = location.href.split("#")[0];
      // let baseUrl = "https://hzq.yoojet.com/";
      // this.codeValue = this.Info.WXCode
      // this.codeValue = baseUrl + '#/SendSMSMobile?id=' + this.billid + '&type=1'
      // this.qrValue = `http://hzq.yoojet.com/#/SendSMSMobile?id=${this.Info.Id}&Type=0`
      // const baseUrl = 'https://hzq.yoojet.com/'
      // let baseUrl = "http://192.168.1.226:8080/"
      // this.qrValue = baseUrl + `#/SendSMS?prop=${this.valueId}&qrcode=${this.Info.QrCode ? this.Info.QrCode :''}&ContentId=${this.Info.TemplateId ? this.Info.TemplateId : '1744533504751833088'}`;
      this.qrValue = this.getQrUrl()
      this.dialogVisible = true
    },
    // 格式化日期格式
    processDate(a) {
      let dateStr = a.split(' ')[0];
      return dateStr.replace(/\//g, '-');
    },
    /**
     * 'view'查看 | 'downLoad'下载
     * 默认查看
    **/
    openInit (id,type ) {
      this.type = type || 'view'
      this.visible = true
      this.loading = true
      this.valueId = id
      if(type === 'downLoad'){
        this.title = '下载'
      }
      // const baseUrl = 'https://hzq.yoojet.com/'

      // this.codeValue = baseUrl + '#/SendSMSMobile?id=' + this.valueId + '&type=2'
      this.$httpp.post('BO/BillList/GetBillDetail', { id: id }).then((res) => {
        console.log(res)
        this.loading = false
        if (res.Success) {
          this.Info = res.Data
          if(res.Data.Imgs && res.Data.Imgs.length){
            this.getImgBase64Data(res.Data.Imgs.split(","))
          } else {
            this.imgList = [];
          }


          // this.codeValue = `http://hzq.yoojet.com?id=${this.Info.Id}&SignType=${this.Info.SignType}&IsPosition=0&Distance=&Type=1`

          this.codeValue= this.getQrUrl()

          const content = JSON.parse(res.Data.Content)
          this.content = content
          const arr = JSON.parse(res.Data.Content).printlist
          console.log('获取arrarrarr ', arr)
          const obj = {}
          arr.forEach((item) => {
            if (item.Keys == 'Title') {
              obj.Name = item.value
            }
            if (item.Keys == 'Salesperson') {
              obj.Maker = item.value
            }
            if (item.Keys == 'Salesperson') {
              obj.Maker = item.value
            }
            if (item.Keys == 'table') {
              console.log('获取table表格数据------------------------------', item.datalist)
              item.datalist.forEach(val=>{
                // var exdate=val.expiryDate?val.expiryDate.substring(0,10):''
                var exdate=val.expiryDate?this.processDate(val.expiryDate) :''
                // this.$set(val,'expiryDate',val.expiryDate?val.expiryDate.substring(0,10):'')
                this.$set(val,'expiryDate',new Date(val.ManufactureDate)>new Date('2024-06-30') ? exdate : '')
              //   格式化保质期日期格式
              //   if(val.expiryDate !=='' || val.expiryDate !==null){
              //     this.$set(val,'expiryDate',new Date(val.ManufactureDate)>new Date('2024-06-30') ? exdate : '')
              //   }
              })
              this.tableInfo = item

              // 备注为空则不显示对应列
              let remarkKey = ''
              let expiryDateKey = ''
              item.columns.forEach(e=>{
                if(e.title === "备注"){
                  remarkKey = e.dataIndex
                }
                if(e.title === "保质期至"){
                  expiryDateKey = e.dataIndex
                }
                // if(e.title === "规格"){
                //   e.title ='规格/包装/等级'
                // }
              })
              if(remarkKey){
                let inx = item.datalist.findIndex((val) => {
                  return val[remarkKey]
                })
                if(inx == -1){
                  item.columns = item.columns.filter(e=>e.dataIndex != remarkKey)
                  content.isRemark = false
                }else{
                  content.isRemark = true
                }
              }
              if(expiryDateKey){
                let inx = item.datalist.findIndex((val) => {
                  return val[expiryDateKey]
                })
                if(inx == -1){
                  item.columns = item.columns.filter(e=>e.dataIndex != expiryDateKey)
                  content.isExpiryDate = false
                }else{
                  content.isExpiryDate = true
                }
              }
              // item.columns.push({
              //   "title": "保质期至",
              //       "dataIndex": "cTMP",
              //       "lineHeight": 20,
              //       "fontSize": 18,
              //       "bold": "initial",
              //       "align": "center",
              //       "textalign": "center",
              //       "textlineHeight": 20,
              //       "width": 80,

              // })
              // item.datalist.forEach(val=>{

              //   this.$set(val,'cTMP','2030-01-01')
              // })
              obj.accompanyingGoodsDetails = item.datalist
              obj.columns = item.columns
            }
            if (item.Keys == 'Custodian') {
              obj.Custodian = item.value
            }
            if (item.Keys == 'Auditor') {
              obj.Auditor = item.value
            }
            if (item.Keys == 'DeptName') {
              obj.DeptName = item.value
            }
            if (item.Keys == 'CustomerName') {
              obj.CusName = item.value
            }
            if (item.Keys == 'CreateTime') {
              obj.DTime = item.value
            }
            if (item.Keys == 'SourceVoucherCode') {
              obj.SourceVoucherCode = item.value
            }
            if (item.Keys == 'ShipmentNumber') {
              obj.ShipmentNumber = item.value
            }
            if (item.Keys == 'Addres') {
              obj.CusAddress = item.value
            }
            if (item.Keys == 'Geter') {
              obj.Geter = item.value
            }
            if (item.Keys == 'Treasurer') {
              obj.Treasurer = item.value
            }
            if (item.Keys == 'Logo') {
              obj.Logo = item.value
            }
            if (item.Keys == 'Remark') {
              obj.Remark = item.value
            }
            if (item.Keys == 'Memo') {
              obj.Remark = item.value
            }
          })
          console.log(obj.accompanyingGoodsDetails)
          console.log(obj.columns)
          console.log(this.tableInfo)
          var list = []
          if (this.tableInfo.rowCount) {
            for (var i = 0; i < this.tableInfo.datalist.length; i += this.tableInfo.rowCount) {
              console.log(this.tableInfo.datalist.slice(i, i + this.tableInfo.rowCount), '数据')
              list.push(this.tableInfo.datalist.slice(i, i + this.tableInfo.rowCount))
            }
          } else {
            list = [...obj.accompanyingGoodsDetails]
          }
          console.log(list)
          this.list = list
          // if (obj.accompanyingGoodsDetails.length > 27) {
          //   obj.accompanyingGoodsDetails.split
          // }
          this.data = obj
          // if(this.data.columns.length>11){
          //   this.cspan=4
          // }else{
          //   this.cspan=3
          // }
        }
      })
    },
    moment,
    numberParseChina (money) {
      // 汉字的数字
      var cnNums = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
      // 基本单位
      var cnIntRadice = ['', '拾', '佰', '仟']
      // 对应整数部分扩展单位
      var cnIntUnits = ['', '万', '亿', '兆']
      // 对应小数部分单位
      var cnDecUnits = ['角', '分', '毫', '厘']
      // 整数金额时后面跟的字符
      var cnInteger = '整'
      // 整型完以后的单位
      var cnIntLast = '圆'
      // 最大处理的数字
      var maxNum = 999999999999999.9999
      // 金额整数部分
      var integerNum
      // 金额小数部分
      var decimalNum
      // 输出的中文金额字符串
      var chineseStr = ''
      // 分离金额后用的数组，预定义
      var parts
      if (money == '') {
        return ''
      }
      money = parseFloat(money)
      if (money >= maxNum) {
        // 超出最大处理数字
        return ''
      }
      if (money == 0) {
        chineseStr = cnNums[0] + cnIntLast + cnInteger
        return chineseStr
      }
      // 转换为字符串
      money = money.toString()
      if (money.indexOf('.') == -1) {
        integerNum = money
        decimalNum = ''
      } else {
        parts = money.split('.')
        integerNum = parts[0]
        decimalNum = parts[1].substr(0, 4)
      }
      // 获取整型部分转换
      if (parseInt(integerNum, 10) > 0) {
        var zeroCount = 0
        var IntLen = integerNum.length
        for (var i = 0; i < IntLen; i++) {
          var n = integerNum.substr(i, 1)
          var p = IntLen - i - 1
          var q = p / 4
          var m = p % 4
          if (n == '0') {
            zeroCount++
          } else {
            if (zeroCount > 0) {
              chineseStr += cnNums[0]
            }
            // 归零
            zeroCount = 0
            chineseStr += cnNums[parseInt(n)] + cnIntRadice[m]
          }
          if (m == 0 && zeroCount < 4) {
            chineseStr += cnIntUnits[q]
          }
        }
        chineseStr += cnIntLast
      }
      // 小数部分
      if (decimalNum != '') {
        var decLen = decimalNum.length
        for (var i = 0; i < decLen; i++) {
          var n = decimalNum.substr(i, 1)
          if (n != '0') {
            chineseStr += cnNums[Number(n)] + cnDecUnits[i]
          }
        }
      }
      if (chineseStr == '') {
        chineseStr += cnNums[0] + cnIntLast + cnInteger
      } else if (decimalNum == '') {
        chineseStr += cnInteger
      }
      return chineseStr
    },
    getQrUrl(){
      const baseUrl = 'https://hzq.yoojet.com/'
          // let baseUrl = "http://192.168.1.226:8080/"
      return baseUrl + `#/SendSMS?prop=${this.valueId}&qrcode=${this.Info.QrCode ? this.Info.QrCode :''}&ContentId=${this.Info.TemplateId ? this.Info.TemplateId : '1744533504751833088'}`;
    },
    downloadPage(){

      this.$message.success("正在生成pdf, 请稍后");
      downloadPDF(this.$refs.pdfContent);
      // this.getPdf('zjcopyPDF', '企业往来对账单')
    },
    getImgBase64Data(list){
      this.$httpp.post('/Base_Manage/Upload/ImageUrlToBase64', list).then((res) => {
        if(res.Data && res.Data.length){
          this.imgList = res.Data
        }
      })
    },
    getAmount(amount){
      console.log(amount,'amount');
      return Math.round(Number(amount) * 100) / 100
    }
  }
}
</script>

<style lang="less" scoped>
.thead {
  td {
    text-align: center;
    padding: 0;
  }
}
.lhthead td {
  text-align: center;
  padding: 0;
  line-height: 17px;
}
.tbody {
  text-align: center;
  td {
    padding: 0;
  }
}
.lhtbody {
  text-align: center;
  td {
    padding: 0;
    line-height: 17px;
  }
}

/deep/ .el-statistic .con .number {
  color: #000 !important;
  font-size: 12px;
  padding: 0;
}
/deep/ .el-statistic .con {
  justify-content: right;
}
.row {
  color: #000 !important;
}
//

@media print {
  @page {
    size: A4 !important;
  }
}
</style>
